package app.auto.designer.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import app.auto.designer.R;
import app.auto.runner.base.Spilt2Util;
import app.auto.runner.base.SubUtil;
import app.auto.runner.base.action.ViewInflater;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.ListBuilder;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.ShareAlert;


public class BottomPopupWindow extends PopupWindow {

    private Button yuyue_btn;
    private View view;
    private View view_white;
    FunCallback funCallback;

    @SuppressLint("WrongConstant")
    public static BottomPopupWindow slideBottom(Activity activity, final View res, final View rview, FunCallback funCallback) {
        final View view = LayoutInflater.from(activity).inflate(R.layout.attr, null);

        final FunCallback finalFunCallback = funCallback;

        ((ViewGroup) view.findViewById(R.id.container)).addView(res);
//        if (rview instanceof TextView && !TextUtils.isEmpty(((TextView) rview).getText())) {
//            ((TextView) view.findViewById(R.id.view_name)).setText(rview.getClass().getSimpleName() + " ("+((TextView) rview).getText()+")");
//        } else {
        ((TextView) view.findViewById(R.id.view_name)).setText(rview.getClass().getSimpleName());
//        }
        final BottomPopupWindow bottomPopupWindow = new BottomPopupWindow(activity, view);
        final List<Map> maplist = (List) res.getTag(R.id.tag_data);
        bottomPopupWindow.setAnimationStyle(R.style.slide_from_bottom);
        funCallback = new FunCallback() {
            @Override
            public void simpleRun(Object aty) {
                super.simpleRun(aty);
                if (aty == null) {
                    return;
                }
                for (int i = 0; i < maplist.size(); i++) {
                    Map m = maplist.get(i);
                    String obj = (String) m.get("uiflag");
                    if (!TextUtils.isEmpty(obj)) {
                        if (obj.equals("bold")) {
                            continue;
                        }
                    } else {
                        String attr = (String) m.get("attr");
                        if (attr.startsWith(aty.toString())) {
                            ((ListView) res).setSelection(i);
                            return;
                        }
                    }
                }
            }
        };

//        AnimationSet an = new AnimationSet(true);
////        an.addAnimation(AnimationUtils.loadAnimation(activity,R.anim.dcloud_slide_in_from_bottom));
//        an.addAnimation(AnimationUtils.loadAnimation(activity,R.anim.dcloud_slide_out_beyond_bottom));
//an.setAnimationListener(new Animation.AnimationListener() {
//    @Override
//    public void onAnimationStart(Animation animation) {
//
//    }
//
//    @Override
//    public void onAnimationEnd(Animation animation) {
//        bottomPopupWindow.getContentView().setVisibility(View.INVISIBLE);
//        bottomPopupWindow.dismiss();
//
//    }
//
//    @Override
//    public void onAnimationRepeat(Animation animation) {
//
//    }
//});
//an.setFillAfter(true);
////        view.setAnimation(an);
//view.setTag(R.id.ani,an);
        bottomPopupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        final ListBuilder rangeEdit = ListBuilder.build()
                .add("a").add("b").add("c").add("d").add("e").add("f").add("g").add("h")
                .add("i").add("j").add("k").add("l").add("m").add("n").add("o").add("p").add("q").add("r")
                .add("s").add("t").add("u").add("v").add("w").add("x").add("y").add("z");
        final List range = rangeEdit.get();
        ((TextView) view.findViewById(R.id.attr_name)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                ShareAlert.delAlert((Activity) view.getContext(), new FunCallback() {
                    @Override
                    public void simpleRun(Object aty) {
                        super.simpleRun(aty);
                        bottomPopupWindow.dismiss();
                        Intent intent = new Intent(v.getContext(), ViewActivity.class).putExtra("action", "del");
                        v.getContext().startActivity(intent);

                    }
                });
            }
        });
        view.findViewById(R.id.control).setTag(R.id.tag_flag, new Stack());
        view.findViewById(R.id.lefthalf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View left) {

                List outlist = (List) ((TextView) view.findViewById(R.id.righthalf_outer)).getTag(R.id.tag_flag);
                if (outlist == null) {
                    outlist = new ArrayList();
                }
                String outend = ((TextView) view.findViewById(R.id.righthalf)).getText().toString().substring(((TextView) view.findViewById(R.id.righthalf)).getText().length() - 1);
//                ((TextView) view.findViewById(R.id.righthalf_outer)).setText(">");

                outlist.add(outend);
                ((TextView) view.findViewById(R.id.righthalf_outer)).setTag(R.id.tag_flag, outlist);
                ((TextView) view.findViewById(R.id.righthalf_outer)).setVisibility(View.VISIBLE);
                ((TextView) view.findViewById(R.id.lefthalf_outer)).setVisibility(View.INVISIBLE);

                String text = ((TextView) left).getText().toString();
                String right = ((TextView) view.findViewById(R.id.righthalf)).getText().toString();
                if (right.endsWith(text.substring(0, 1))) {
                    return;
                }

                List list = (List) ((TextView) left).getTag(R.id.tag_data);

                List filterRt = SubUtil.getSub(maplist, "attr", list, "starts");
                res.setTag(R.id.tag_data, filterRt);
                ((BaseAdapter) ((ListView) res).getAdapter()).notifyDataSetChanged();
                Spilt2Util.splitAlpha(text, range, true, (TextView) view.findViewById(R.id.lefthalf), (TextView) view.findViewById(R.id.righthalf), new FunCallback() {
                    @Override
                    public void simpleRun(Object aty) {
                        super.simpleRun(aty);


                    }
                }.setParam(text));
                Stack stack = (Stack) view.findViewById(R.id.control).getTag(R.id.tag_flag);
                stack.push(text);

                visible_view_control(view);

            }
        });

        view.findViewById(R.id.righthalf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View right) {
                List outlist = (List) ((TextView) view.findViewById(R.id.lefthalf_outer)).getTag(R.id.tag_flag);
                if (outlist == null) {
                    outlist = new ArrayList();
                }

                String outend = ((TextView) view.findViewById(R.id.lefthalf)).getText().toString().substring(0, 1);
//                ((TextView) view.findViewById(R.id.lefthalf_outer)).setText("<");

                outlist.add(outend);
                ((TextView) view.findViewById(R.id.lefthalf_outer)).setTag(R.id.tag_flag, outlist);
                ((TextView) view.findViewById(R.id.righthalf_outer)).setVisibility(View.INVISIBLE);
                ((TextView) view.findViewById(R.id.lefthalf_outer)).setVisibility(View.VISIBLE);

                String text = ((TextView) right).getText().toString();
                String left = ((TextView) view.findViewById(R.id.lefthalf)).getText().toString();
                if (left.endsWith(text.substring(0, 1))) {
                    return;
                }

                List list = (List) ((TextView) right).getTag(R.id.tag_data);

                List filterRt = SubUtil.getSub(maplist, "attr", list, "starts");
                res.setTag(R.id.tag_data, filterRt);
                ((BaseAdapter) ((ListView) res).getAdapter()).notifyDataSetChanged();
                Spilt2Util.splitAlpha(text, range, true, (TextView) view.findViewById(R.id.lefthalf), (TextView) view.findViewById(R.id.righthalf), new FunCallback() {
                    @Override
                    public void simpleRun(Object aty) {
                        super.simpleRun(aty);


                    }
                }.setParam(text));
                Stack stack = (Stack) view.findViewById(R.id.control).getTag(R.id.tag_flag);
                stack.push(text);

                visible_view_control(view);
            }
        });

        view.findViewById(R.id.control).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View tview) {
                String text;
                if (((TextView) view.findViewById(R.id.control)).getVisibility() == View.VISIBLE) {


                    Stack stack = (Stack) view.findViewById(R.id.control).getTag(R.id.tag_flag);
                    if (stack.size() == 1) {
                        return;
                    }
                    visible_view_control(view);
                    stack.pop();
                    text = (String) stack.peek();
                    List list = (List)
                            range.subList(range.indexOf(text.substring(0, 1)), range.indexOf(text.substring(text.length() - 1)) + 1);

                    List filterRt = SubUtil.getSub(maplist, "attr", list, "starts");
                    res.setTag(R.id.tag_data, filterRt);
                    ((BaseAdapter) ((ListView) res).getAdapter()).notifyDataSetChanged();
                    Spilt2Util.splitAlpha(text, range, true, (TextView) view.findViewById(R.id.lefthalf), (TextView) view.findViewById(R.id.righthalf), new FunCallback() {
                        @Override
                        public void simpleRun(Object aty) {
                            super.simpleRun(aty);


                        }
                    }.setParam(text));
                    List listleft = (List) ((TextView) view.findViewById(R.id.lefthalf_outer)).getTag(R.id.tag_flag);
                    if (!((TextView) view.findViewById(R.id.lefthalf_outer)).getText().toString().isEmpty() && ((TextView) view.findViewById(R.id.lefthalf_outer)).getVisibility() == View.VISIBLE) {
                        String alphabetleft;
                        if (listleft.size() >= 2) {
                            alphabetleft = (String) listleft.get(listleft.size() - 2);
                        } else {
                            alphabetleft = "";
                        }
//                        ((TextView) view.findViewById(R.id.lefthalf_outer)).setText("<");
                        listleft.remove(listleft.size() - 1);
                    }

                    List listright = (List) ((TextView) view.findViewById(R.id.righthalf_outer)).getTag(R.id.tag_flag);
                    if (!((TextView) view.findViewById(R.id.righthalf_outer)).getText().toString().isEmpty() && ((TextView) view.findViewById(R.id.righthalf_outer)).getVisibility() == View.VISIBLE) {
                        String alphabetright;
                        if (listright.size() >= 2) {
                            alphabetright = (String) listright.get(listright.size() - 2);
                        } else {
                            alphabetright = "";
                        }
                        listright.remove(listright.size() - 1);
//                        ((TextView) view.findViewById(R.id.righthalf_outer)).setText(">");
                    }

                } else {
                    text = ((TextView) view.findViewById(R.id.center)).getText().toString();

                    Spilt2Util.splitAlpha(text, range, true, (TextView) view.findViewById(R.id.lefthalf), (TextView) view.findViewById(R.id.righthalf), new FunCallback() {
                        @Override
                        public void simpleRun(Object aty) {
                            super.simpleRun(aty);


                        }
                    }.setParam(text));
                    ((TextView) view.findViewById(R.id.center)).setText("·");
                    Stack stack = (Stack) view.findViewById(R.id.control).getTag(R.id.tag_flag);
                    stack.push(text);

                }

                visible_view_control(view);
            }
        });


        view.findViewById(R.id.control).performClick();

        view.findViewById(R.id.recent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((ListView) res).setSelection(0);
            }
        });
        view.findViewById(R.id.layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < maplist.size(); i++) {
                    Map m = maplist.get(i);
                    if (m.get("uiflag") != null) {
                        continue;
                    }
                    String attr = (String) m.get("attr");
                    attr = attr.split(":")[1];
                    if (attr.startsWith("layout")) {
                        ((ListView) res).setSelection(i);
                        break;
                    }

                }


            }
        });

        view.findViewById(R.id.margin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < maplist.size(); i++) {
                    Map m = maplist.get(i);
                    if (m.get("uiflag") != null) {
                        continue;
                    }
                    String attr = (String) m.get("attr");
                    attr = attr.split(":")[1];
                    if (attr.startsWith("layout_margin")) {
                        ((ListView) res).setSelection(i);
                        break;
                    }

                }


            }
        });
        view.findViewById(R.id.padding).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < maplist.size(); i++) {
                    Map m = maplist.get(i);
                    if (m.get("uiflag") != null) {
                        continue;
                    }
                    String attr = (String) m.get("attr");
                    attr = attr.split(":")[1];
                    if (attr.startsWith("padding")) {
                        ((ListView) res).setSelection(i);
                        break;
                    }

                }


            }
        });


        final MapBuilder mapBuilder = MapBuilder.build()
                .add("LineaLayout", ListBuilder.build().add("orientation").add("weightSum"))
                .add("ScrollView", ListBuilder.build().add("scrollbars").add("fillViewport"))
                .add("TextView", ListBuilder.build().add("maxLength").add("textSize").add("textStyle").add("textColor").add("ellipse").add("lines"))
                .add("ImageView", ListBuilder.build().add("src").add("background").add("scaleType"))
                .add("EditText", ListBuilder.build().add("hint").add("hintColor"))
                .add("ListView", ListBuilder.build().add("divider").add("cacheColorHint").add("smoothScrollbar").add("scrollbars").add("choiceMode").add("listSelector").add("smoothScrollbar").add("fastScrollEnabled"))
                .add("GridView", ListBuilder.build().add("columnWidth").add("verticalSpacing").add("horizontalSpacing").add("stretchMode").add("numColumns").add("choiceMode").add("listSelector").add("smoothScrollbar").add("fastScrollEnabled"));

        if (view.findViewById(R.id.text) != null) {
            if (mapBuilder.get().containsKey(rview.getClass().getSimpleName())) {

                ((TextView) view.findViewById(R.id.text)).setText(rview.getClass().getSimpleName().replace("View", "").replace("Layout", "").toLowerCase());
                view.findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
                    int i = -1;

                    @Override
                    public void onClick(View v) {
                        i++;
                        ListBuilder listBuilder = (ListBuilder) mapBuilder.get().get(rview.getClass().getSimpleName());
                        List list = listBuilder.get();
                        if (i == list.size()) {
                            i = 0;
                        }
                        String s = list.get(i).toString();


                        for (int i = 0; i < maplist.size(); i++) {
                            Map m = maplist.get(i);
                            if (m.get("uiflag") != null) {
                                continue;
                            }
                            String attr = (String) m.get("attr");
                            attr = attr.split(":")[1];
                            if (attr.startsWith(s)) {
                                ((ListView) res).setSelection(i);
                                break;
                            }

                        }


                    }
                });
            } else {
                view.findViewById(R.id.text).setVisibility(View.GONE);
//                ((ViewGroup) view.findViewById(R.id.text).getParent()).removeView(view.findViewById(R.id.text));
            }
        }
        return bottomPopupWindow;
    }

    @SuppressLint("WrongConstant")
    @NonNull
    public static void visible_view_control(View view) {
        Stack stack = (Stack) view.findViewById(R.id.control).getTag(R.id.tag_flag);
        if (stack.size() > 1) {
            view.findViewById(R.id.control).setVisibility(View.VISIBLE);
        } else {
            view.findViewById(R.id.control).setVisibility(View.INVISIBLE);
        }
        return;
    }

    private static void merge(String text, List range, TextView viewById, TextView viewById1) {
        SpannableString span1 = new SpannableString(text.substring(0, 1) + viewById.getText().toString().substring(1));
        SpannableString span2 = new SpannableString(viewById.getText().toString().substring(0, viewById.getText().length() - 1) + text.substring(text.length() - 1));
        span1.setSpan(new AbsoluteSizeSpan(1), span1.length() - 2, span1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span2.setSpan(new AbsoluteSizeSpan(1), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        viewById.setText(span1);
        viewById1.setText(span2);
        String[] headt = text.replaceAll(" ", "").split("·");
        String h = headt[0].substring(0, 1);
        String t = headt[headt.length - 1].substring(headt[headt.length - 1].length() - 1);
        String splitX = "";
        int hi = range.indexOf(h);
        int ti = range.indexOf(t);
        int count = ti - hi + 1;
        int midi;
        if (count % 2 == 0) {
            midi = count / 2;
        } else {
            midi = count / 2;
        }

        viewById.setTag(com.aliang.auto.R.id.tag_data, range.subList(0, midi));
        viewById1.setTag(com.aliang.auto.R.id.tag_data, range.subList(midi, range.size()));

    }


    @SuppressLint("WrongConstant")
    public BottomPopupWindow(final Activity activity, final View res) {
        super(activity);

        //设置SelectPicPopupWindow的View
        this.setContentView(res);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高


        PopupWindow window = this;
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        res.findViewById(R.id.pane).getLayoutParams().height = dm.heightPixels * 21 / 48 / 60 * 64;//1/12//21/48 defination
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
//        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为透明
        ColorDrawable dw = new ColorDrawable(00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);

        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                new Handler(Looper.getMainLooper(), new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                        lp.alpha = 1.0f;
                        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        activity.getWindow().setAttributes(lp);
                        return false;
                    }
                }).sendEmptyMessage(0);
            }
        });

    }

}
